<template>
  <div class="user-page-com">
    <div class="filter-contain">
      <el-form
        ref="queryFormRef"
        :model="queryForm"
        label-width="80px"
        label-position="right"
        class="user-filter-form"
        :inline="true"
      >
        <el-form-item prop="originCode" label="组织代码" class="form-input">
          <el-input
            v-model="queryForm.originCode"
            placeholder="请输入组织代码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="originName" label="组织名称" class="form-input">
          <el-input
            v-model="queryForm.originName"
            placeholder="请输入组织名称"
          ></el-input>
        </el-form-item>
        <el-form-item prop="parentId" label="上级组织" class="form-input">
          <el-tree-select
            v-model="queryForm.parentId"
            :data="originTreeOptions"
            :props="originDefaultProps"
            default-expand-all
            check-strictly
            placeholder="请选择上级组织"
          ></el-tree-select>
        </el-form-item>
        <el-form-item prop="status" label="状态" class="form-input">
          <el-select
            clearable
            v-model="queryForm.status"
            placeholder="请选择状态"
          >
            <el-option label="正常" value="0"></el-option>
            <el-option label="禁用" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="tableLoading"
            @click="handleQuery"
          >
            <template #icon>
              <i-ep-search />
            </template>
            查询</el-button
          >
          <el-button
            type="default"
            @click="handleReset"
            :loading="tableLoading"
          >
            <template #icon>
              <i-ep-refreshLeft />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-btn-contain">
      <el-button type="primary" @click="handleAdd">
        <template #icon>
          <i-ep-plus />
        </template>
        新增
      </el-button>
      <el-dropdown @command="handleStatusCommand">
        <el-button type="default">
          <template #icon>
            <i-ep-editPen />
          </template>
          状态变更
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="0">开启</el-dropdown-item>
            <el-dropdown-item command="1">禁用</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <div class="table-contain">
      <kt-table
        :tableData="tableData"
        :tableColumns="tableColumns"
        :page-number="queryForm.pageNumber"
        :page-size="queryForm.pageSize"
        :total="queryForm.total"
        showPagination
        @selection-change="handleSelectionChange"
        @getList="getList"
      >
        <template #statusStr="{ row }">
          <el-tag
            v-if="row.status === '0'"
            type="success"
            size="default"
            class="table-tag"
            >{{ row.statusStr }}</el-tag
          >
          <el-tag
            v-else-if="row.status === '1'"
            type="danger"
            size="default"
            class="table-tag"
            >{{ row.statusStr }}</el-tag
          >
        </template>
        <template #action="{ row }">
          <el-button
            type="primary"
            @click="handleEdit(row)"
            class="table-btn"
            link
          >
            <template #icon>
              <i-ep-edit />
            </template>
            编辑
          </el-button>
          <el-button
            type="primary"
            @click="handleView(row)"
            class="table-btn"
            link
          >
            <template #icon>
              <i-ep-view />
            </template>
            查看
          </el-button>
        </template>
      </kt-table>
    </div>
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      :before-close="clearDialog"
      width="50%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="dialogFormRef"
        :model="dialogForm"
        label-width="120px"
        label-position="right"
        :disabled="dialogType === 2"
        inline
        :rules="dialogFormRules"
        class="dialog-user-form"
      >
        <el-form-item prop="originCode" label="组织代码" class="form-input">
          <el-input
            disabled
            v-model="dialogForm.originCode"
            placeholder="系统自动生成"
          ></el-input>
        </el-form-item>
        <el-form-item prop="parentId" label="上级组织" class="form-input">
          <el-tree-select
            v-model="dialogForm.parentId"
            :data="originTreeOptions"
            :props="originDefaultProps"
            default-expand-all
            check-strictly
            placeholder="请选择上级组织"
          >
          </el-tree-select>
        </el-form-item>
        <el-form-item prop="originName" label="组织名称" class="form-input">
          <el-input
            v-model="dialogForm.originName"
            placeholder="请输入组织名称"
          ></el-input>
        </el-form-item>
        <el-form-item prop="originUserId" label="组织联系人" class="form-input">
          <el-select
            v-model="dialogForm.originUserId"
            placeholder="选择组织联系人"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.userNumber"
              :label="item.userName + '（' + item.userNumber + '）'"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="originEmail" label="组织邮箱" class="form-input">
          <el-input
            v-model="dialogForm.originEmail"
            placeholder="请输入组织邮箱"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="originBusinessPhone"
          label="组织联系电话"
          class="form-input"
        >
          <el-input
            v-model="dialogForm.originBusinessPhone"
            placeholder="请输入组织联系电话"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button :loading="submitLoading" @click="closeDialog"
          >取消</el-button
        >
        <el-button :loading="submitLoading" type="primary" @click="handleSubmit"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  getOrigins,
  updateOrigin,
  updateOriginStatus,
  addOrigin
} from "@/api/origin"
import { getUserInfo } from "@/api/user"

import { buildTree } from "@/utils/tools"
import { ElMessage } from "element-plus"

const originDefaultProps = {
  children: "children",
  label: "originName"
}

// 新增：初始表单对象副本
const initQueryForm = {
  originCode: "",
  originName: "",
  parentId: "",
  status: "",
  pageSize: 20,
  pageNumber: 1,
  total: 0
}
const initDialogForm = {
  originCode: "",
  parentId: 0,
  originName: "",
  originEmail: "",
  originBusinessPhone: "",
  originUserId: "",
  parentCode: ""
}

const selectedRows = ref<any>([])
const dialogVisible = ref(false)
const dialogTitle = ref("")
const dialogType = ref(0) // 0:新增 1:编辑 2:查看
const dialogFormRef = ref()
// 修改为使用初始对象副本
const dialogForm = ref({ ...initDialogForm })
const dialogFormRules = {
  originName: [{ required: true, message: "请输入组织名称", trigger: "blur" }],
  parentId: [{ required: true, message: "请选择上级组织", trigger: "change" }],
  originEmail: [{ required: true, message: "请输入组织邮箱", trigger: "blur" }],
  originBusinessPhone: [
    { required: true, message: "请输入组织联系电话", trigger: "blur" }
  ],
  originUserId: [
    { required: true, message: "请选择组织联系人", trigger: "change" }
  ]
}
const submitLoading = ref(false)
const tableLoading = ref(false)
const tableData = ref([])
const queryFormRef = ref()
const originTreeList = ref<any[]>([]) // 上级组织下拉选项（List）
const originTreeOptions = ref<any[]>([]) // 上级组织下拉选项
const userOptions = ref<any[]>([]) // 组织联系人下拉选项
// 修改为使用初始对象副本
const queryForm = ref({ ...initQueryForm })
const tableColumns = [
  {
    prop: "selection",
    type: "selection",
    width: "55px",
    fixed: "left"
  },
  {
    label: "组织代码",
    prop: "originCode"
  },
  {
    label: "组织名称",
    prop: "originName"
  },
  {
    label: "组织状态",
    prop: "statusStr"
  },
  {
    label: "上级组织",
    prop: "parentOriginStr"
  },
  {
    label: "组织邮箱",
    prop: "originEmail"
  },
  {
    label: "组织联系人",
    prop: "originUserStr"
  },
  {
    label: "组织联系电话",
    prop: "originBusinessPhone"
  },
  {
    label: "最近修改时间",
    prop: "updatedAt"
  },
  {
    label: "最近修改人",
    prop: "updatedUserStr"
  },
  {
    label: "创建时间",
    prop: "createdAt"
  },
  {
    label: "创建人",
    prop: "createdUserStr"
  },
  {
    label: "操作",
    prop: "action",
    width: "200px",
    fixed: "right",
    slotName: "action"
  }
]

// 条件查询
const handleQuery = () => {
  queryForm.value.pageNumber = 1
  getList({
    pageNumber: 1
  })
}
// 重置查询条件
const handleReset = () => {
  // 使用初始对象副本重置
  queryForm.value = { ...initQueryForm, pageSize: queryForm.value.pageSize }
  const form = queryFormRef.value
  if (form) {
    form.resetFields()
  }
  getList()
}
// 选择条目
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows
}
// 处理状态变更
const handleStatusCommand = (status: string) => {
  handleStatusChange(status)
}
// 新增组织
const handleAdd = () => {
  dialogVisible.value = true
  dialogTitle.value = "新增组织"
  dialogType.value = 0
  // 使用初始对象副本重置
  dialogForm.value = { ...initDialogForm }
  const form = dialogFormRef.value
  if (form) {
    form.clearValidate()
  }
}
// 编辑用户
const handleEdit = (row: any) => {
  dialogVisible.value = true
  dialogTitle.value = "编辑用户"
  dialogType.value = 1
  dialogForm.value = { ...row }
  const form = dialogFormRef.value
  if (form) {
    form.clearValidate()
  }
}
// 查看用户
const handleView = (row: any) => {
  dialogVisible.value = true
  dialogTitle.value = "查看用户"
  dialogType.value = 2
  dialogForm.value = { ...row }
  const form = dialogFormRef.value
  if (form) {
    form.clearValidate()
  }
}
// 弹窗确认
const handleSubmit = () => {
  const form = dialogFormRef.value
  if (form) {
    form.validate((valid: boolean) => {
      if (valid) {
        // 提交表单
        submitLoading.value = true
        try {
          const postData = {
            ...dialogForm.value,
            parentId: dialogForm.value.parentId || 0 // 确保parentId有值
          }
          if (postData.parentId === 0) {
            postData.parentCode = "0" // 如果没有上级组织，则设置parentCode为0
          } else {
            const parent = originTreeList.value.find(
              (item: any) => item.originId === postData.parentId
            )
            postData.parentCode = parent ? parent.originCode : "0"
          }
          if (dialogType.value === 0) {
            addOriginFn(postData)
          } else if (dialogType.value === 1) {
            updateOriginFn(postData)
          } else {
            dialogVisible.value = false
          }
        } catch (error) {
          ElMessage.error("提交失败，请稍后重试！")
          console.error(error) // eslint-disable-line
        } finally {
          submitLoading.value = false
        }
      } else {
        ElMessage.error("请填写完整信息")
      }
    })
  }
}
// 关闭弹窗
const closeDialog = () => {
  dialogVisible.value = false
  clearDialog()
}
// 关闭弹窗前的操作
const clearDialog = () => {
  const form = dialogFormRef.value
  if (form) {
    form.resetFields()
  }
  // 使用初始对象副本重置
  dialogForm.value = { ...initDialogForm }
}
// 获取组织信息(param可选)
const getList = async (param: any = {}) => {
  const tempParam = param || {}
  if (tempParam.isAll) {
    try {
      const res = await getOrigins({})

      let originList = res.data.rows
      originList = originList.map((item: any) => {
        item.value = item.originId
        return item
      })
      const treeData = [
        {
          originId: 0,
          originCode: "0",
          value: 0,
          originName: "根组织",
          children: buildTree(originList, "originId", "parentId")
        }
      ]
      originTreeList.value = res.data.rows
      originTreeOptions.value = treeData
    } catch (error) {
      ElMessage.error("获取组织信息失败，请稍后重试！")
      console.error(error) // eslint-disable-line
    } finally {
      tableLoading.value = false
    }
  } else {
    queryForm.value = {
      ...queryForm.value,
      ...tempParam
    }
    tableLoading.value = true
    try {
      const res = await getOrigins(queryForm.value)
      tableData.value = res.data.rows
      queryForm.value.total = res.data.total
    } catch (error) {
      ElMessage.error("获取组织信息失败，请稍后重试！")
      console.error(error) // eslint-disable-line
    } finally {
      tableLoading.value = false
    }
  }
}
// 新增组织信息
const addOriginFn = async (data: any) => {
  try {
    const res = await addOrigin(data)
    if (res.code !== 200) {
      ElMessage.error(res.msg)
      return
    }
    ElMessage.success("新增成功")
    dialogVisible.value = false
    getList()
    getList({
      isAll: true // 刷新上级组织列表
    })
  } catch (error) {
    ElMessage.error("新增用户失败，请稍后重试！")
    console.error(error) // eslint-disable-line
  }
}
// 编辑用户信息
const updateOriginFn = async (data: any) => {
  try {
    const res = await updateOrigin(data)
    if (res.code !== 200) {
      ElMessage.error(res.msg)
      return
    }
    ElMessage.success("编辑成功")
    dialogVisible.value = false
    getList()
    getList({
      isAll: true // 刷新上级组织列表
    })
  } catch (error) {
    ElMessage.error("编辑用户失败，请稍后重试！")
    console.error(error) // eslint-disable-line
  }
}
// 批量冻结/注销/恢复用户
const handleStatusChange = async (status: string) => {
  if (selectedRows.value.length === 0) {
    ElMessage.error("请至少选择一条数据")
    return
  }
  try {
    const res = await updateOriginStatus({
      ids: selectedRows.value.map((item: any) => item.originId),
      status
    })
    if (res.code !== 200) {
      ElMessage.error(res.msg)
      return
    }
    ElMessage.success("操作成功")
    getList()
  } catch (error) {
    ElMessage.error("操作失败，请稍后重试！")
    console.error(error) // eslint-disable-line
  }
}

// 获取组织联系人信息
const getUserList = async () => {
  try {
    const res = await getUserInfo({})
    if (res.code !== 200) {
      ElMessage.error(res.msg)
      return
    }
    userOptions.value = res.data.rows
  } catch (error) {
    ElMessage.error("获取组织联系人信息失败，请稍后重试！")
    console.error(error) // eslint-disable-line
  }
}

// 组件挂载后获取用户信息
onMounted(() => {
  getList() // 列表
  getList({
    // 上级组织内容
    isAll: true
  })
  getUserList() // 组织联系人
})
</script>

<style lang="scss" scoped>
.user-page-com {
  height: 100%;
  @apply flex flex-col;
  .filter-contain {
    @apply h-auto;
  }
  .table-btn-contain {
    @apply h-auto pb-4;
    :deep(.el-button) {
      @apply mr-4;
    }
  }
  .table-contain {
    @apply flex-1;
  }
}
</style>
